//
//  Pokemon.swift
//  PokeMon-main
//
//  Created by 安爹的Mac on 16/7/17.
//  Copyright © 2016年 安爹的苹果机. All rights reserved.
//

import Foundation

class Pokemon {
    private var _name: String!
    private var _pokedexId: Int!
    private var _type: String!
    private var _description: String!
    private var _height: String!
    private var _defense: String!
    private var _weight: String!
    private var _attack: String!
    private var _nextEvolutionText: String!
    private var _nextEvolutionLevel: String!
    private var _nextEvolutionPokeDex: String!
    private var _pokemonUrl: String!
    
    var nextEvoTxt: String {
        if _nextEvolutionText == nil {
            _nextEvolutionText = ""
        }
        return _nextEvolutionText

    }
    
    var nextEvoId: String {
        if _nextEvolutionPokeDex == nil {
            _nextEvolutionPokeDex = ""
        }
        return _nextEvolutionPokeDex
    }
    
    var nextEvoLvl: String {
        if _nextEvolutionLevel == nil {
            _nextEvolutionLevel = ""
        }
        return _nextEvolutionLevel
    }
    
    var description: String {
        if _description == nil {
            _description = ""
        }
        return _description
    }
    
    var height: String {
        if _height == nil {
            _height = ""
        }
        return _height
    }
    
    var type: String {
        if _type == nil {
            _type = ""
        }
        return _type
    }
    
    var defense: String {
        if _defense == nil {
            _defense = ""
        }
        return _defense
    }
    
    var weight: String {
        if _weight == nil {
            _weight = ""
        }
        return _weight
    }
    
    var attack: String {
        if _attack == nil {
            _attack = ""
        }
        return _attack
    }
    
    var name: String {
        return _name
    }
    
    var pokedexId: Int {
        return _pokedexId
    }
    
    init(name: String, pokedexId: Int) {
        self._name = name
        self._pokedexId = pokedexId
        _pokemonUrl = "\(URL_BASE)\(POKEMON_URL)/\(self._pokedexId)/"
    }
    
    func downloadPokemonDetails(completed: DownloadComplete) {
        var dict: NSDictionary!
        let url = NSURL(string: _pokemonUrl)!
        print(_pokemonUrl)
        let req = NSMutableURLRequest(URL: url)
        req.HTTPMethod = "GET"
        req.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
        let session = NSURLSession.sharedSession()
        print("进入下载过程")
        session.dataTaskWithRequest(req) { (data: NSData?, resp: NSURLResponse?, err: NSError?) in
            //print(resp.debugDescription)
        
        if err == nil {
            do {
                dict = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as! NSDictionary
                // print(dict)
                

                
                if let weight = dict["weight"] as? String {
                    self._weight = weight
                }
                
                if let height = dict["height"] as? String {
                    self._height = height
                }
                
                if let attack = dict["attack"] as? Int {
                    self._attack = "\(attack)"
                }
                
                if let defense = dict["defense"] as? Int {
                    self._defense = "\(defense)"
                }
                
                print(self._height)
                print(self._weight)
                print(self._attack)
                print(self._defense)
                
                if let types = dict["types"] as? Array<NSDictionary> {
                    self._type = ""
                    if types.count > 1 {
                        for i in 0..<types.count {
                            if let name = types[i]["name"] {
                                self._type = self._type + "/\(name.capitalizedString)"
                            }
                        }
                    }
                } else {
                    self._type = ""
                }
                print(self._type)
                
                if let description = dict["descriptions"] as? Array<NSDictionary> where description.count > 0 {
                    if let uri = description[0]["resource_uri"] {
                        let url = NSURL(string: "\(URL_BASE)\(uri)")
                        let session = NSURLSession.sharedSession()
                        session.dataTaskWithURL(url!, completionHandler: { (data: NSData?, resp: NSURLResponse?, err: NSError?) in
                            if err == nil {
                                do {
                                    let dic = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments) as! NSDictionary
                                    if let decr = dic["description"] as? String {
                                        self._description = decr
                                        print(self._description)
                                        completed()
                                    }
                                } catch {
                                    print("description got an error!")
                                }
                            }
                        }).resume()
                    } else {
                        self._description = ""
                    }
                    
                }
                
                if let evolution = dict["evolutions"] as? Array<NSDictionary> where evolution.count > 0 {
                    if let to = evolution[0]["to"] as? String {
                        if to.rangeOfString("mega") == nil {
                            self._nextEvolutionText = to
                            if let uri = evolution[0]["resource_uri"] as? String {
                                let newStr = uri.stringByReplacingOccurrencesOfString("/api/v1/pokemon/", withString: "")
                                let idx = newStr.stringByReplacingOccurrencesOfString("/", withString: "")
                                self._nextEvolutionPokeDex = idx
                                if let lvl = evolution[0]["level"] as? Int {
                                    self._nextEvolutionLevel = "\(lvl)"
                                    print(self._nextEvolutionLevel)
                                    print(self._nextEvolutionPokeDex)
                                    print(self._nextEvolutionText)
                                }
                            }
                        }
                    
                    } else {
                        self._nextEvolutionText = ""
                        self._nextEvolutionPokeDex = ""
                        self._nextEvolutionLevel = ""
                    }
                    
                }
                
                       } catch {
                print("something wrong!")
            }
        }
        
        }.resume()
        
    }
    
    
}